package com.xixi.demo.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.nio.charset.StandardCharsets;
import java.util.UUID;
@Slf4j
public class SecurityUtils {
    /**
     * 加密
     * @param password
     * @return
     */
    public static String encrypt(String password){
        //生成盐值
        String salt = UUID.randomUUID().toString().replace("-","");
        //使用md5加密: 盐值+密码
        String secretString = DigestUtils.md5DigestAsHex((salt+password).getBytes(StandardCharsets.UTF_8));
        return salt+secretString;
    }

    public static Boolean verity(String password, String finalPassword){
        if(!StringUtils.hasLength(password) || !StringUtils.hasLength(finalPassword)){
            return false;
        }
        if(finalPassword.length() != 64){
            log.error("密码长度不足");
        }
        String salt = finalPassword.substring(0, 32);
        String secretString = DigestUtils.md5DigestAsHex((salt+password).getBytes(StandardCharsets.UTF_8));
        return (salt + secretString).equals(finalPassword);
    }
}
